const OpenAI = require('openai')
const fs = require('fs')
const readline = require('readline')
// const { aiChat } = require('./utils/aiChat')

const openai = new OpenAI({
    // baseURL: 'https://api.deepseek.com/v1',
    // apiKey: 'sk-2a18c38b0d284ef4a318e960de9663db'
  apiKey: 'f4875c7d-b8c6-4da0-a903-b7391cb1a66d',
  baseURL: 'https://ark.cn-beijing.volces.com/api/v3/bots',
})

module.exports.chat = async (message) => {
	const completion = await openai.chat.completions.create({
		messages: [
			{ role: "user", content: message }
		],
		model: "bot-20250314144904-rrnhv",
	})
	return completion.choices[0].message.content
}

let messageList = [
  { role: "system", content: '你是一个和蔼慈祥的胖老头' }
]

async function test() {
	const completion = await openai.chat.completions.create({
		messages: messageList,
		// model: "deepseek-chat",
		model: "bot-20250314144904-rrnhv",
		stream: true,
    temperature: 0.9,
	})
  let str = ''
	for await (const chunk of completion) {
    process.stdout.write(chunk.choices[0]?.delta?.content || "")
    str += chunk.choices[0]?.delta?.content
  }
  messageList.push({
    role: "assistant", content: `${str}`
  })
	// fs.writeFile('answer.txt', JSON.stringify(process.stdout), (err) => {
	// 	if (err) throw err;
	// 	console.log('文件已被保存');
	// })
	console.log("\n\n以上是我的回答，请合理参考，祝您生活愉快！\n\n")
	// return completion.choices[0].message.content
}

function bootstrap() {
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
  });

  console.log("我是一个智能助手，你可以向我提问任何问题，我将尽力回答。  \n\n")

  rl.on("line", async (input) => {
    // 输入q或者Ctrl+C退出程序
   if (input === "q") {
      rl.close();
      return;
    }
    messageList.push({
      role: "user", content: input
    })
    test()
    // aiChat(input)
  });

  rl.on("close", () => {
    console.log("\nBye!");
    process.exit(0);
  });
}
try {
  bootstrap();
} catch (error) {
  console.error(error);
  process.exit(1);
}

// test()
